<?php
/**
 * Laundries Controller
 * 
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package controllers
 */
class LaundriesController extends AppController {
	/**
    * @var string Controller name (faster in PHP 4)
    */
	var $name = 'Laundries';
	
	/**
    * @var string Scaffolding on prefix 
    */	
	var $scaffold = 'admin';
	
	/**
    * @var array Paginate settings
    */
	var $paginate = array(         
		'limit' => 10,                
		'order' => array(           
			'Laundry.name' => 'asc'        
		)    
	);
	
	/**
	 * Callback function _beforeScaffold
	 * 
	 * Get triggered after init Scaffolding.
	 */
	function _beforeScaffold() {
		if(!empty($this->params['prefix']) && $this->params['prefix'] == 'admin') {
			unset($this->viewVars['associations']['hasMany']['Measurement']);
		}		
		return true;
	}
	
	/**
	 * Function add
	 * 
	 * Controller action
	 */
	function add() {
		$countries = $this->Laundry->Country->find('list');
		$this->set(compact('countries'));
		if($this->data) {
			$this->Laundry->create();
			$this->Laundry->set($this->data);
			if($this->Laundry->validates()) {
				if($this->Laundry->save()) {
					$this->Laundry->habtmAdd('User', $this->Laundry->id, $this->Auth->user('id')); 
					$this->Session->setFlash("Laundry has been created.");            
					$this->redirect(array('controller' => 'laundries', 'action' => 'index'));
				}
			}
		}
	}
	
	/**
	 * Function index
	 * 
	 * Controller action
	 */
	function index() {
		$showusers = 5;
		$laundries = $this->Laundry->findByUserId($this->Auth->user('id'));
		$data = $this->paginate('Laundry', array(
			'Laundry.id' => $laundries
		));
		$this->set(compact('data', 'showusers'));
	}
	
	/**
	 * Function edit
	 * 
	 * Controller action
	 */
	function edit($id = null) {
		$this->beforeFilterCheckLaundryAccess($id);
		
		$countries = $this->Laundry->Country->find('list');
		$this->set(compact('countries'));
		
		$this->Laundry->id = $id;
		if (empty($this->data)) {
			$this->data = $this->Laundry->read();
		} else {
			if ($this->Laundry->save($this->data)) {
				$this->Session->setFlash('Your laundry has been updated.');
				$this->redirect(array('controller' => 'laundries', 'action' => 'index'));
			}
		}
	}
}